package com.dz.risk.config;


import com.dz.risk.common.SysConstant;
import com.dz.risk.dao.RiskFactorDao;
import com.github.benmanes.caffeine.cache.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 装配caffeine
 * @className CaffeineConfig
 * @description TODO
 * @date 2021/3/29 14:07
 */

@Configuration
@Slf4j
@Component
public class CaffeineConfig {
    /**
     * 缓存的 key 过期
     */
    public static final String EXPIRED = "EXPIRED";

    @Autowired
    RiskFactorDao riskFactorDao;
    @Autowired
    MsgConfig msgConfig;


    /**
     * 缓存 配置
     * @return
     */
    @Bean(value = "caffeineCache")
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(msgConfig.getHourOut(), TimeUnit.HOURS)
                // 初始的缓存空间大小
                .initialCapacity(msgConfig.getInitialCapacity())
                // 缓存的最大条数
                .maximumSize(msgConfig.getMaximumSize())
                .build();
    }

    /**
     * 启动项目后 加载表名
     */
    @PostConstruct
    public void init() {
        log.info("初始化缓存数据......");
//        List<RiskFactorEntity> list = riskFactorDao.selectList(null);
//        Map<String, String> map = new HashMap();
//        map.put("t_st_risk_factor", "t_st_risk_factor");
//        map.put("t_st_risk_factor_value", "t_st_risk_factor_value");
//        this.caffeineCache().putAll(map);
        //加载数据库数据
    }

    public Object getKey(String key) {
        Object ifPresent = this.caffeineCache().getIfPresent(key);
        if (null == ifPresent && SysConstant.ZERO == getAll().size()) {
            init();
            return this.caffeineCache().getIfPresent(key);
        }
        return ifPresent;
    }

    public void putKey(String key, String value) {
        this.caffeineCache().put(key, value);
    }

    public void del(String key) {
        this.caffeineCache().invalidate(key);
    }

    public ConcurrentMap<@NonNull String, Object> getAll() {
        return this.caffeineCache().asMap();
    }

}
